#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2019/9/21 0021 19:11
# @Author  : GXl
# @File    : __init__.py
# @Software: win10 Tensorflow1.13.1 python3.7


from flask import Flask,g,abort
from flask_sqlalchemy import SQLAlchemy
from flask_httpauth import  HTTPTokenAuth
from flask_moment import Moment
from config import Config
from utils.apiutils import *
from flask_migrate import Migrate
from flask_redis import FlaskRedis
from werkzeug.exceptions import HTTPException,default_exceptions



db = SQLAlchemy()
moment = Moment()
config= Config()
#redis客户端
redis_client = FlaskRedis()

# 引入基础认证、token认证模块
auth = HTTPTokenAuth(scheme='JWT',header='Access-Token')

app = Flask(__name__)
def create_app():
    #配置初始化
    config.init_app(app)
    moment.init_app(app)
    Migrate(app, db)
    db.init_app(app)
    logutils.init_app(app)
    redis_client.init_app(app)

    from .main import main as main_blueprint
    app.register_blueprint(main_blueprint)

    from .book import book as book_blueprint
    app.register_blueprint(book_blueprint, url_prefix='/api/book')

    #全局错误处理，确保即便是错误页，返回的也是个json数据
    def error_handling(error):
        if isinstance(error,HTTPException):
            result = { "code":error.code,"description":error.description,"message":str(error)}
        else:
            description = abort.mapping[500].description
            result = {"code": 500, "description":description, "message": str(error)}

        resp = jsonify(result)
        resp.status_code = result["code"]
        return resp

    for code in default_exceptions.keys():
        app.register_error_handler(code,error_handling)
    return app
#全局认证模块

# 根据token登录认证装饰器进行请求携带的token校验
@auth.verify_token
def verify_token(token):
    from .models import User
    user = User.verify_auth_token(token)
    if not user:
        return False
    #用户信息装入本次请求中
    g.user = user
    return True


@auth.error_handler
def auth_error(status):
    return jsonerror("Access Denied",status=status), status